<style rel="stylesheet/scss" lang="scss" scoped>
	#diyMapcontent {
		width: 500px;
		height: 0px;
	}

	.i-w-50 {
		width: 400px;
	}

	.sp-w-50 {
		line-height: 40px;
		width: 100px;
		display: inline-block;
	}
	.i-w--select{
		width: 194px;
	}
	.inline-input{
		width: 400px;
	}
	
</style>
<template>
	<!--添加地址 -->
	<el-dialog :title="title" :visible.sync="centerDialogVisible" width="60%" center>
		<el-row class="p-all-20 dig-box">
			<el-col :span="20" class="box-flex m-b-10">
				<span class="sp-w-50 m-r-10">店名:</span>
				<el-input placeholder="请输入店名" v-model="keyword" class="i-w-50" maxLength="20"/>
			</el-col>
			<el-col :span="20" class="box-flex m-b-10">
				<span class="sp-w-50 m-r-10">区域:</span>
				<template>
				  <el-select v-model="proValue" placeholder="请选择" class="i-w--select m-r-10" @change="selectProFn">
					<el-option
					  v-for="item in provinceList"
					  :key="item.id"
					  :label="item.name"
					  :value="item.id">
					</el-option>
				  </el-select>
				</template>
				<template>
				<el-select v-model="cityValue" placeholder="请选择" class="i-w--select" @change="selectCityFn">
					<el-option
					v-for="item in cityList"
					:key="item.id"
					:label="item.name"
					:value="item.id">
					</el-option>
				</el-select>
				</template>
			</el-col>
			<el-col :span="20" class="box-flex m-b-10">
				<span class="sp-w-50 m-r-10">地址:</span>
				<!-- <el-input placeholder="请输入地址" v-model="region" class="i-w-50" maxLength="80"/> -->
				<el-autocomplete
					
					class="inline-input"
					v-model="region"
					:fetch-suggestions="querySearch"
					placeholder="请输入详细地址"
					:trigger-on-focus="false"
					@select="handleSelect"
				>
				</el-autocomplete>
			</el-col>
			<el-col :span="20" class="box-flex m-b-10">
				<span class="sp-w-50 m-r-10">顺序:</span>
				<el-input v-model="sort" class="i-w-50" type="number" maxLength="5" oninput="if(value.length>5)value=value.slice(0,5)"/>
			</el-col>
			<!-- <el-col  class="box-flex m-b-10">
				<span class="sp-w-50 m-r-10">搜索附近:</span>
				<el-input v-model="lagName" class="i-w-50" placeholder="请输入地址锁定范围添加坐标" />
				<el-button type="primary" @click="searchKeyword" class="m-l-10" size="mini">搜索</el-button>
			</el-col> -->
			<el-col :span="20" class="box-flex m-b-10">
				<div id="diyMapcontent"></div>
			</el-col>
		</el-row>
		<span slot="footer" class="dialog-footer">
			<el-button @click="closeMapLayer" size="mini">取 消</el-button>
			<el-button type="primary" @click="saveAddress" size="mini">确 定</el-button>
		</span>
	</el-dialog>
</template>
<script>
	import {
		getToken
	} from '@/utils/auth'
	import {
		SUCCESS_REQUEST_STATUS
	} from '@/utils/config.js'
	export default {
		props: {
			info: {
				type: Object,
				default: {}
			},
			title: {
				type: [String],
				default: '新建店铺'
			}
		},
		data() {
			return {
				sort: '',
				region: '',
				keyword: '',
				lagName: '',
				map: [],
				proValue:'',
				cityValue:'',
				markers: [],
				searchService: [],
				longitude: '',
				latitude: '',
				shopId: '',
				provinceList: [],
				cityList: [],
				geocoder: null,
				cityId: '',
				provinceId: '',
				restaurants:[],
				centerDialogVisible: true
			}
		},
		mounted() {
			console.log(this.info)
			if(this.info.longitude) {
				this.sort  = this.info.sort
				this.region = this.info.address
				this.keyword = this.info.name
				this.shopId = this.info.id
				this.longitude = this.info.longitude
				this.latitude = this.info.latitude
				if(this.info.provinceid){
					this.cityId = this.info.cityid
					this.provinceid = this.info.provinceid
					this.getQueryCity()
				}
			}
			
			setTimeout(() => {
				this.initMap()
			}, 500)
			this.getQueryprovince()
			

		},
		methods: {
			querySearch(queryString, cb) {
				this.restaurants = []
				this.searchKeyword()
				let result = []
        setTimeout(() => {
					
					
					cb(this.restaurants);
				},1000)
      },
      createFilter(queryString) {
        return (restaurant) => {
					console.log(restaurant)
          return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        };
      },
      
      handleSelect(item) {
        console.log(item);
				this.longitude = item.lng
				this.latitude = item.lat
      },
			selectProFn(e){
				console.log(e)
				
				
				this.provinceid = e
				this.provinceList.forEach((item, index) => {
					if(item.id == this.provinceid) {
						this.proValue = item.name
					}
				})
				console.log(this.proValue)
				this.cityId = ''
				this.cityValue = ''
				this.getQueryCity()
			},
			selectCityFn(e) {
				this.cityId = e
				this.cityList.forEach((item, index) => {
					if(item.id == this.cityId) {
						this.cityValue = item.name
					}
				})
				console.log(this.cityValue)
			},
			// 获取省份信息
			getQueryprovince() {
				this.$ajax({
					api: 'address/queryprovince'
				}).then(res => {
					console.log(res)
					if(res.status === SUCCESS_REQUEST_STATUS) {
						this.provinceList = res.data.region
						if(this.provinceid) {
							this.provinceList.forEach((item, index) => {
								if(item.id == this.provinceid) {
									this.proValue = item.name
								}
							})
						}
						
					}
				})
			},
			// 获取城市数据
			getQueryCity() {
				this.$ajax({
					api: 'address/querycity',
					params: {
						provinceId: this.provinceid
					}
				}).then(res => {
					if(res.status === SUCCESS_REQUEST_STATUS) {
						this.cityList = res.data.region
						console.log(this.cityList)
						if(this.cityId && this.cityList.length>0) {
							this.cityList.forEach((item, index) => {
								if(this.cityId == item.id) {
									this.cityValue =  item.name
								}
							})
						}
					}
				})
			},
			closeMapLayer() {
				this.$emit('closeMapLayer')
			},
			saveAddress() {
				let attr = !this.keyword ? '请填写店铺名称': !this.region ? '请填写地址' : !this.sort ? '请填写顺序号': !this.longitude ? '需要选择地理位置才能保持': !this.provinceid ? '请选择省份':!this.cityId ? '请选择城市':''
				if(attr) {
					this.$message({
						type: 'error',
						message: attr
					})
					return
				}
				console.log(this.region)
				this.$ajax({
					api: 'merchant/shop/add',
					params: {
						name: this.keyword,
						address: this.region,
						sort: this.sort,
						provinceId: this.provinceid,
						cityId: this.cityId,
						longitude: this.longitude,
						latitude: this.latitude,
						token: getToken(),
						merchantUserId: window.localStorage.getItem('merchantUserId') ? window.localStorage.getItem('merchantUserId') : '',
						shopId: this.shopId,
					}
				}).then(res => {
					console.log(res)
					if(res.status === SUCCESS_REQUEST_STATUS) {
						this.$message({
							type: 'success',
							message:'添加成功'
						})
						this.$emit('saveAddress')
					}
				}).catch(err => {
					console.log(err)
					this.$message({
						type: 'error',
						message: err.messsage
					})
				})
				
			},
			initMap() {
				let _this = this
				let center = new qq.maps.LatLng(23.12908,113.26436)
				console.log(document.getElementById('diyMapcontent'))
				console.log(44)
				_this.map = new qq.maps.Map(document.getElementById('diyMapcontent'), {
					center: new qq.maps.LatLng(this.latitude?this.latitude:23.12908, this.longitude?this.longitude:113.26436),
					zoom: 13
				})
				var latlngBounds = new qq.maps.LatLngBounds();
				//调用Poi检索类
				_this.searchService = new qq.maps.SearchService({
					complete : function(results){
						console.log(results)
						
            var pois = results.detail.pois;
						if(results.detail.pois && results.detail.pois.length>0) {
							for(var i = 0,l = pois.length;i < l; i++){
								 let addrseeObj = {
									 value: pois[i].address,
									 name: pois[i].address,
									 lat: pois[i].latLng.lat,
									 lng: pois[i].latLng.lng
								 }
								 _this.restaurants.push(addrseeObj)

							}
            }
						console.log(_this.restaurants)
            
        },
				
					
// 					//设置搜索范围为北京restaurant
// 					location: "广州",
// 					//设置搜索页码为1
// 					pageIndex: 1,
// 					//设置每页的结果数为5
// 					pageCapacity: 1,
// 					//设置展现查询结构到infoDIV上
// 					// panel: document.getElementById("infoDiv"),
// 					//设置动扩大检索区域。默认值true，会自动检索指定城市以外区域。
// 					autoExtend: true,
// 					complete: function (results) {
// 						var pois = results.detail.pois;
// 						console.log(pois)
// 						if(!pois){
// 							return
// 						}
// 						for (var i = 0, l = 1; i < l; i++) {
// 							var poi = pois[i];
// 							latlngBounds.extend(poi.latLng);
// 							var marker = new qq.maps.Marker({
// 								map: _this.map,
// 								position: poi.latLng
// 							})
// 							console.log(pois[i])
// 							marker.setTitle(pois[i].address?pois[i].address : pois[i].name)
// 							_this.latitude = poi.latLng.lat
// 							_this.longitude = poi.latLng.lng
// 							_this.markers.push(marker);
// 							console.log(_this.markers)
// 							info.setPosition(poi.latLng);
// 							_this.map.setCenter(poi.latLng);
// 						}
// 					}

				});
				var info = new qq.maps.InfoWindow({
					map: _this.map
				});
				_this.geocoder = new qq.maps.Geocoder({
					complete: function (result) {
						console.log(result)
						_this.map.setCenter(result.detail.location);
						var marker = new qq.maps.Marker({
							map: _this.map,
							position: result.detail.location
						});
						var info = new qq.maps.InfoWindow({
							map: _this.map
						});
						if(result) {
							_this.longitude = result.detail.location.lng
							_this.latitude = result.detail.location.lat
						}
						
						_this.markers.push(marker);
						//添加监听事件 当标记被点击了设置图层
						qq.maps.event.addListener(marker, 'mouseover', function () {
							info.open();
							info.setContent('<div style="width:280px;height:60px;">' +
								result.detail.address + '</div>');
							info.setPosition(result.detail.location);
						});
						_this.lagName = result.detail.address
						qq.maps.event.addListener(marker, 'mouseout', function () {
							info.close();
							
						});
					}
				});
				//绑定单击事件添加参数
				qq.maps.event.addListener(_this.map, 'click', function (event) {
					console.log(event)
					var latLng = new qq.maps.LatLng(event.latLng.getLat(), event.latLng.getLng());
					_this.latitude = event.latLng.getLat()
					_this.longitude = event.latLng.getLng()
					console.log(_this.latitude)
					//调用信息窗口
					var info = new qq.maps.InfoWindow({
						map: _this.map
					})
					//调用获取位置方法
					console.log(latLng)
					_this.clearOverlays(_this.markers);
					_this.geocoder.getAddress(latLng);
				});
			},
			clearOverlays(overlays) {
				var overlay;
				while (overlay = overlays.pop()) {
					overlay.setMap(null);
				}
			},
			searchKeyword() {
				if(!this.proValue || !this.cityValue) {
					this.$message({
						type:'error',
						message:'请选择省份城市'
					})
					return
				}
				if(!this.region){
					this.$message({
						type:'error',
						message:'请输入附近地址'
					})
					return
				}
				this.clearOverlays(this.markers);
				//this.region = `${this.proValue}${this.cityValue}${this.region}`
				this.searchService.setLocation(`${this.proValue}${this.cityValue}`);
				this.searchService.search(this.region);
				
				console.log(this.region)
				//this.geocoder.getLocation(this.lagName);
			}
		},
		watch: {
			centerDialogVisible(val) {
				console.log(val)
				if(!val) {
					this.$emit('closeMapLayer')
				}
			}
		}
	}
</script>
